class Solution {
public:
    int getCnt(vector<int>& nums, int k) {
        int n = nums.size();
        int l = 0,r = 0;
        int ans = 0;
        int number = 0;
        unordered_map<int,int> hash;
        
        while(r < n) {
            if(!hash.count(nums[r]) || hash[nums[r]] == 0){
                number++;
            }
            hash[nums[r]]++;
            
            while(number > k){
                hash[nums[l]]--;
                if(hash[nums[l]] == 0){
                    number--;
                }
                l++;
            }
            ans += r - l;
            r++;
            
        }
        return ans;
    }                                 
    int subarraysWithKDistinct(vector<int>& nums, int k) {
        return getCnt(nums,k) - getCnt(nums,k-1);
    }
};
